package com.yunhoo.pay.bean;

import com.ibatis.dao.client.DaoManager;
import com.yunhoo.asset.util.PayCodeConstants;
import com.yunhoo.base.bean.FinancialProjectBean;
import com.yunhoo.base.db.dao.DepartmentDao;
import com.yunhoo.base.db.dao.FinancialProjectDao;
import com.yunhoo.base.model.Department;
import com.yunhoo.base.model.FinancialProject;
import com.yunhoo.base.model.PayStyle;
import com.yunhoo.pay.db.impl.AbroadGroupImpl;
import com.yunhoo.pay.db.impl.LoanBillImpl;
import com.yunhoo.pay.db.impl.VoucherPubImpl;
import com.yunhoo.pay.model.CostItemAccount;
import com.yunhoo.pay.model.Expense;
import com.yunhoo.pay.model.QueryVouchers;
import com.yunhoo.pay.model.VouCheckInfo;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.Disabled;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.NavigationTool;
import com.yunhoo.sys.util.common.Null;
import com.yunhoo.sys.util.common.ToolKit;
import com.yunhoo.sys.db.config.DaoConfig;
import com.yunhoo.sys.util.tree.TreeUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFooter;
import org.apache.poi.hssf.usermodel.HSSFHeader;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.richfaces.component.UIDataTable;
import org.richfaces.event.TreeSelectionChangeEvent;

/**
 *
 * @author Administrator
 */
@ManagedBean(name = "loanbill")
@SessionScoped
public class LoanBillBean {

    private LinkedList<Expense> linkedli = new LinkedList<Expense>();
    private List<Expense> loanbilllist = new ArrayList<Expense>();//翻页数据集
    private DataModel loanbillModel = new ListDataModel();
    private DataModel loanCheckViewModel = new ListDataModel();
    private Expense exp = new Expense();  //审核页面Exp
    private UIDataTable payData = null;
    private UIDataTable checkData = null;
    private boolean addOrUpdate;
    private boolean showAble = true;
    private boolean deleteable = false;
    private boolean saveOrNot = false;
    private boolean updateOrNot = false;
    private boolean submitOrNot = true;
    private boolean getFirstOrNot = true;
    private QueryVouchers qlb = new QueryVouchers();
    private List<CostItemAccount> expacc = new ArrayList();
    private ListDataModel model = new ListDataModel(expacc);
    private int index;
    private Disabled dis = new Disabled();
    private String payWay;
    private String payWayType;
    private List<SelectItem> payStyleList;
    private static String nameSpace = "loanbill.";
    private static DaoManager daom;
    private static DepartmentDao dao;
    private static FinancialProjectDao finProjdao;
    private DataModel<FinancialProject> finProjModel = null;
    private String status = "";

    public LoanBillBean() {
        daom = DaoConfig.getDaoManager();
        dao = (DepartmentDao) daom.getDao(DepartmentDao.class);
        finProjdao = (FinancialProjectDao) daom.getDao(FinancialProjectDao.class);
        initStatus();
        initPayStyleList();
        initFinProjList();//预算项目列表
        initDate();
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -10);
        Date begin = calendar.getTime();
        Date end = new Date();
        qlb.setNumDateStart(begin);
        qlb.setNumDateEnd(end);
    }

    private void initStatus() {
        saveOrNot = true;
        addOrUpdate = true;
        deleteable = true;
        updateOrNot = true;
        submitOrNot = true;
        showAble = true;
        getFirstOrNot = true;
        this.setExp(new Expense());
        loanbilllist = IbatisTemplate.queryForList(nameSpace + "queryLoanBillForCheck", curOrgCode().trim());
        //loanbillModel.setWrappedData(loanbilllist);
    }

    private void initFinProjList() {
        if (finProjModel == null) {
            finProjModel = new ListDataModel<FinancialProject>();
        }
        try {
            List<FinancialProject> finli = finProjdao.queryAll(new FinancialProject(true));
            finProjModel.setWrappedData(finli);
        } catch (SQLException ex) {
            Logger.getLogger(FinancialProjectBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    //支付方式选择列表
    public final void initPayStyleList() {
        List<PayStyle> Styleli = AbroadGroupImpl.getPaystyleli();
        payStyleList = new ArrayList();
        for (PayStyle d : Styleli) {
            payStyleList.add(new SelectItem(d.getCode(), d.getName()));
        }
    }

    public void payWayChange(ValueChangeEvent event) {
        String code = (String) event.getNewValue();
        exp.getPayStyle().setCode(code);
        List<PayStyle> li = AbroadGroupImpl.getPaystyleli();
        if (!Null.check(li) && !Null.check(code)) {
            for (PayStyle l : li) {
                if (code.trim().equals(l.getCode().trim())) {
                    exp.setPayStyle(l);
                    payWayType = l.getType().trim();
                }
            }
        }
    }

    public void changeCashPaid() {
        if (!Null.check(exp.getPayStyle().getType())) {
            if (exp.getPayStyle().getType().equals("0")) {
                exp.setCashPaid("1");
            } else {
                exp.setCashPaid("0");
            }
        }
    }

    public void getFirst() {
        if (linkedli.size() == 0) {
            if (loanbilllist.isEmpty()) {
                //System.out.println("没有要审核的单据!");
                ToolKit.msgs_info("没有要审核的单据");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(loanbilllist);
                this.setExp(linkedli.getFirst());

                exp.setCheckaccount(exp.getTotal());
                dis.setFirst(true);
                dis.setPreviouse(true);
                dis.setNext(false);
                dis.setLast(false);
            }
            if (exp.getNumberStatus().trim().equals("0")) {
                submitOrNot = true;
            } else {
                submitOrNot = false;
            }
        } else {
            this.setExp(linkedli.getFirst());
            exp.setCheckaccount(exp.getTotal());
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        deleteable = false;
        updateOrNot = false;
        index = 0;
        defaults();
    }

    public void getLast() {
        if (linkedli.size() == 0) {
            if (loanbilllist.isEmpty()) {
                //System.out.println("没有要审核的单据!");
                ToolKit.msgs_info("没有要审核的单据");
                FacesContext.getCurrentInstance().renderResponse();
            } else {
                linkedli.clear();
                linkedli.addAll(loanbilllist);
                this.setExp(linkedli.getLast());
                exp.setCheckaccount(exp.getTotal());
                dis.setLast(true);
                dis.setNext(true);
                dis.setPreviouse(false);
                dis.setFirst(false);
            }
            if (exp.getNumberStatus().trim().equals("0")) {
                submitOrNot = true;
            } else {
                submitOrNot = false;
            }
        } else {
            this.setExp(linkedli.getLast());
            exp.setCheckaccount(exp.getTotal());
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        index = linkedli.size() - 1;
        defaults();
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void next() {
        if (index < linkedli.size() - 1) {
            index = index + 1;
            this.setExp(linkedli.get(index));
            //System.out.println("numbers:" + exp.getNumberStatus());
            defaults();
            exp.setCheckaccount(exp.getTotal());
            dis.setFirst(false);
            dis.setPreviouse(false);
            //System.out.println("this index:" + index);
        } else {
            ToolKit.msgs_info("没有了!");
            dis.setLast(true);
            dis.setNext(true);
            dis.setFirst(false);
            dis.setPreviouse(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void previouse() {
        if (index > 0) {
            index -= 1;
            this.setExp(linkedli.get(index));
            defaults();
            exp.setCheckaccount(exp.getTotal());
            dis.setNext(false);
            dis.setLast(false);
        } else {
            ToolKit.msgs_info("没有了!");
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
            FacesContext.getCurrentInstance().renderResponse();
        }
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void checkandRep() {
        if (exp.getCostitem().getCode() == null) exp.getCostitem().setCode("");
        if (exp.getBudgetSource() == null) exp.setBudgetSource("");
        if (exp.getCostClass() == null) exp.setCostClass("");
        if (exp.getCostTypes().getCode() == null) exp.getCostTypes().setCode("");
        if (exp.getPaycode() == null) exp.setPaycode("");

        if (exp.getAuditDate() == null || Null.check(exp.getAuditor())) {
            ToolKit.msgs_err("您无权限审核！");
        } else {
            pass();
            gobackCheck();
        }
    }

    public void checkPayandRep() {
        String payeStatus = exp.getNumberStatus();
        exp.setNumberStatus("2");
        if (Null.check(exp.getPayStyle().getCode())) {
            ToolKit.msgs_err("请选择支付方式");
        } else if (Null.check(exp.getPayaccount())) {
            ToolKit.msgs_err("请输入支付金额");
        } else if (exp.getPayDate() == null) {
            ToolKit.msgs_err("请选择支付日期");
        } else if ("1".equals(payWayType) && Null.check(exp.getReceive())) {
            ToolKit.msgs_err("收款人不能为空!");
        } else if (exp.getCashPaid() == null) {
            ToolKit.msgs_err("是否现金付讫！");
        } else if (Null.check(payeStatus)) {
            ToolKit.msgs_err("是否支付完毕！");
        } else if ("1".equals(exp.getCashPaid()) && exp.getTicketcode().length() != 0) {
            ToolKit.msgs_err("现金付讫不需填写支付凭证号");
        } else if ("0".equals(exp.getCashPaid()) && Null.check(exp.getTicketcode())) {
            ToolKit.msgs_err("请填写支付凭证号");
        } else {
            if ("0".equals(exp.getCashPaid())) {
                String str = exp.getNumber() + exp.getTicketcode();
                exp.setTicketcode(str);
            }
            exp.setNumberStatus(payeStatus);
            pay();
            NavigationTool.getSelectedUrl("/page/pay/payment/table/queryloanbill.xhtml");
        }
    }

    public void pass() {
        exp.setNumberStatus("2");
        exp.setAuditor(curPerNum().trim());

        LoanBillImpl.updateLoanBillForCheck(exp);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        info.setCheckInfo(exp.getCheckInfo());
        VoucherPubImpl.insertCheckInfo(info);
    }

    private void initCheckValue(Expense exp) {
        this.exp = exp;
        defaults();
        exp.setCheckaccount(exp.getTotal());
        if (exp.getCostitem().getCode() == null) exp.getCostitem().setCode("");
        if (exp.getBudgetSource() == null) exp.setBudgetSource("");
        if (exp.getCostClass() == null) exp.setCostClass("");
        if (exp.getCostTypes().getCode() == null) exp.getCostTypes().setCode("");
        if (exp.getPaycode() == null) exp.setPaycode("");
    }

    public void passWithParam(Expense exp) {
        initCheckValue(exp);

        exp.setNumberStatus("2");
        exp.setAuditor(curPerNum().trim());

        LoanBillImpl.updateLoanBillForCheck(exp);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        info.setCheckInfo(exp.getCheckInfo());
        VoucherPubImpl.insertCheckInfo(info);
    }

    public void pay() {
        exp.setPayer(curPerNum().trim());
        LoanBillImpl.updateLoanBillForPay(exp);
        queryloanbillPay();
    }

    public void rescind() {
        IbatisTemplate.update(nameSpace + "voucherRescind", exp);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        VoucherPubImpl.deleteCheckInfo(info);

        initStatus();
        loanbillModel.setWrappedData(loanbilllist);
        NavigationTool.getSelectedUrl("/page/pay/check/table/queryloanbill.xhtml");
    }

    public void cancel() {
        initStatus();
        loanbillModel.setWrappedData(loanbilllist);
        qlb = new QueryVouchers();
        status = "";
    }

    public void payrescind() {
        IbatisTemplate.update(nameSpace + "payVoucherRescind", exp);
        initStatus();
        loanbillModel.setWrappedData(loanbilllist);
        NavigationTool.getSelectedUrl("/page/pay/payment/table/queryloanbill.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void back() {
        Map map = new HashMap();
        map.put("number", exp.getNumber().trim());
        map.put("orgCode", curOrgCode().trim());
        IbatisTemplate.update(nameSpace + "voucherBack", map);

        VouCheckInfo info = new VouCheckInfo();
        info.setBillNum(exp.getNumber());
        info.setVouType(exp.getVoutype());
        info.setCheckInfo(exp.getCheckInfo());
        VoucherPubImpl.insertCheckInfo(info);

        gobackCheck();
    }

    public void goBackPayList() {
        queryloanbillPay();
        NavigationTool.getSelectedUrl("/page/pay/payment/table/queryloanbill.xhtml");
    }

    public void gobackCheck() {
        queryloanbillCheck();
        NavigationTool.getSelectedUrl("/page/pay/check/table/queryloanbill.xhtml");
    }

    public void showcheckdetail() {
        this.setExp((Expense) this.loanbillModel.getRowData());
        index = this.loanbillModel.getRowIndex();
        linkedli.clear();
        linkedli.addAll(loanbilllist);
        defaults();
        exp.setCheckaccount(exp.getTotal());
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        NavigationTool.getSelectedUrl("/page/pay/check/operation/loanbill.xhtml");
    }

    public void showPayDetail() {
        this.setExp((Expense) this.loanbillModel.getRowData());
        index = this.loanbillModel.getRowIndex();
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        linkedli.clear();
        linkedli.addAll(loanbilllist);

        defaults();

        NavigationTool.getSelectedUrl("/page/pay/payment/operation/loanbill.xhtml");
    }

    public void contype(ValueChangeEvent event) {
        String voutype = event.getNewValue().toString();
    }

    //选择预算项目
    public void selectProjForQuery() {
        FinancialProject fProj = finProjModel.getRowData();
        qlb.getProject().setFinCode(fProj.getFinCode());
        qlb.getProject().setFinName(fProj.getFinName());
    }

    //选择部门
    public void selecteDeptForQuery(TreeSelectionChangeEvent event) {
        Department dp = (Department) TreeUtil.listener(event);
        qlb.getDept().setCode(dp.getCode());
        qlb.getDept().setName(dp.getName());
    }

    public void queryloanbillCheck() {
        loanbilllist = LoanBillImpl.queryListCheck(qlb);
        loanbillModel.setWrappedData(loanbilllist);
    }

    public void queryloanbillPay() {
        loanbilllist = LoanBillImpl.queryListPay(qlb);
        loanbillModel.setWrappedData(loanbilllist);
    }

    public void buildpaycode() {
        if (!exp.getCostitem().getCode().trim().equals("")) {
            if (exp.getBudgetSource() != null) {
                if (exp.getCostClass() != null) {
                    if (!exp.getCostTypes().getCode().trim().equals("")) {
                        String pcode = PayCodeConstants.buildPayCodeForLoanBill(exp);
                        exp.setPaycode(pcode);
                    } else {
                        ToolKit.msgs_err("请选择支出渠道");
                    }
                } else {
                    ToolKit.msgs_err("请选择支出类别");
                }
            } else {
                ToolKit.msgs_err("请选择预算来源");
            }
        } else {
            ToolKit.msgs_err("请选择经济分类");
        }
    }

    public void exportExcelForCheck() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("审核单据借款单列表");
        String[] excelColumns = initTabeleHeader();
        List<Expense> rows = loanbilllist;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("审核单据借款单列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (Expense row : rows) {
            createTableRow(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        LoanBillBean.exportExcel(demoWorkBook, demoSheet);

    }

    //初始化表头信息
    public String[] initTabeleHeader() {
        String[] excelColumns = {"单据编号", "单据状态", "单据日期", "借款事由", "借款金额", "预算项目", "借款人", "部门", "支出类别",
            "预算来源", "经济分类", "支出渠道", "支付令", "核定金额", "审核日期", "审核人", "支付金额", "支付日期", "出纳"};
        return excelColumns;
    }

    public static void createTableRow(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, Expense elb, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式
        HSSFCellStyle dstyled = demoWorkBook.createCellStyle();
        dstyled.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));


        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(elb.getNumber()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.functionNumberStatus().get(elb.getNumberStatus())));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertDate(elb.getNumDate()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(elb.getAffair()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertDouble(elb.getTotal()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(5);
        cell.setCellValue(PayCodeConstants.convertString(elb.getProject().getFinName()));
        cell = row.createCell(6);
        cell.setCellValue(PayCodeConstants.convertString(elb.getUser().getCpsn_name()));
        cell = row.createCell(7);
        cell.setCellValue(PayCodeConstants.convertString(elb.getDept().getName()));
        cell = row.createCell(8);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.formateCostClass().get(elb.getCostClass())));
        cell = row.createCell(9);
        cell.setCellValue(PayCodeConstants.convertString(elb.getBudgetSource()));
        cell = row.createCell(10);
        cell.setCellValue(PayCodeConstants.convertString(elb.getCostitem().getName()));
        cell = row.createCell(11);
        cell.setCellValue(PayCodeConstants.convertString(elb.getCostTypes().getName()));
        cell = row.createCell(12);
        cell.setCellValue(PayCodeConstants.convertString(elb.getPaycode()));
        cell = row.createCell(13);
        cell.setCellValue(PayCodeConstants.convertDouble(elb.getCheckaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(14);
        if (elb.getAuditDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(elb.getAuditDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(15);
        cell.setCellValue(PayCodeConstants.convertString(elb.getAuditor()));
        cell = row.createCell(16);
        cell.setCellValue(PayCodeConstants.convertDouble(elb.getPayaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(17);
        if (elb.getPayDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(elb.getPayDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(18);
        cell.setCellValue(PayCodeConstants.convertString(elb.getPayer()));

    }

    public static void exportExcel(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos = null;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exportExcelForPay() {
        HSSFWorkbook demoWorkBook = new HSSFWorkbook();
        HSSFSheet demoSheet = demoWorkBook.createSheet("支付单据借款单列表");
        String[] excelColumns = initTabeleHeaderForPay();
        List<Expense> rows = loanbilllist;

        HSSFHeader header = demoSheet.getHeader();
        header.setCenter("支付单据借款单列表");
        HSSFRow headerRow = demoSheet.createRow(0);
        for (int i = 0; i < excelColumns.length; i++) {
            HSSFCell headerCell = headerRow.createCell((short) i);
            //headerCell.setEncoding(HSSFCell.ENCODING_UTF_16);
            headerCell.setCellValue(excelColumns[i]);
        }
        //填充数据
        int rowIndex = 1;
        for (Expense row : rows) {
            createTableRowForPay(demoWorkBook, demoSheet, row, rowIndex);
            rowIndex++;
        }
        LoanBillBean.exportExcelForPay(demoWorkBook, demoSheet);

    }
    //初始化表头信息

    public String[] initTabeleHeaderForPay() {
        String[] excelColumns = {"单据编号", "单据状态", "单据日期", "借款事由", "借款金额", "预算项目", "借款人", "部门", "支出类别",
            "预算来源", "经济分类", "支出渠道", "支付令", "核定金额", "审核日期", "审核人", "支付方式", "支票号", "支付金额", "支付日期", "出纳"};
        return excelColumns;
    }

    public static void createTableRowForPay(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet, Expense elbp, int rowIndex) {
        //创建第rowIndex行
        CreationHelper createHelper = demoWorkBook.getCreationHelper();
        HSSFCellStyle dstyle = demoWorkBook.createCellStyle();
        dstyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));//格式
        HSSFCellStyle dstyled = demoWorkBook.createCellStyle();
        dstyled.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));

        HSSFCell cell = null;
        HSSFRow row = demoSheet.createRow(rowIndex);
        cell = row.createCell(0);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getNumber()));
        cell = row.createCell(1);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.functionNumberStatus().get(elbp.getNumberStatus())));
        cell = row.createCell(2);
        cell.setCellValue(PayCodeConstants.convertDate(elbp.getNumDate()));
        cell.setCellStyle(dstyle);
        cell = row.createCell(3);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getAffair()));
        cell = row.createCell(4);
        cell.setCellValue(PayCodeConstants.convertDouble(elbp.getTotal()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(5);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getProject().getFinName()));
        cell = row.createCell(6);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getUser().getCpsn_name()));
        cell = row.createCell(7);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getDept().getName()));
        cell = row.createCell(8);
        cell.setCellValue(PayCodeConstants.convertString(PayCodeConstants.formateCostClass().get(elbp.getCostClass())));
        cell = row.createCell(9);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getBudgetSource()));
        cell = row.createCell(10);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getCostitem().getName()));
        cell = row.createCell(11);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getCostTypes().getName()));
        cell = row.createCell(12);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getPaycode()));
        cell = row.createCell(13);
        cell.setCellValue(PayCodeConstants.convertDouble(elbp.getCheckaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(14);
        if (elbp.getAuditDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(elbp.getAuditDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(15);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getAuditor()));
        cell = row.createCell(16);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getPayStyle().getCode()));
        cell = row.createCell(17);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getTicketcode()));
        cell = row.createCell(18);
        cell.setCellValue(PayCodeConstants.convertDouble(elbp.getPayaccount()));
        cell.setCellStyle(dstyled);
        cell = row.createCell(19);
        if (elbp.getPayDate() == null) {
            cell.setCellValue("");
        } else {
            cell.setCellValue(PayCodeConstants.convertDate(elbp.getPayDate()));
            cell.setCellStyle(dstyle);
        }
        cell = row.createCell(20);
        cell.setCellValue(PayCodeConstants.convertString(elbp.getPayer()));

    }

    public static void exportExcelForPay(HSSFWorkbook demoWorkBook, HSSFSheet demoSheet) {
        try {
            String strfileName = "book.xls";
            FileOutputStream fos = null;
            //导出
            demoSheet.setGridsPrinted(true);//demoSheet
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " + HSSFFooter.numPages());
            // 获得JSF上下文环境
            FacesContext context = FacesContext.getCurrentInstance();
            // 获得ServletContext对象
            ServletContext servletContext = (ServletContext) context.getExternalContext().getContext();
            // 取得文件的绝对路径
            String excelName = servletContext.getRealPath("/upload") + "/" + strfileName;//strfileName
            File exportFile = new File(excelName);
            fos = new FileOutputStream(exportFile);//fos
            demoWorkBook.write(fos);//demoWorkBook
            fos.close();

            FacesContext ctx = FacesContext.getCurrentInstance();
            ctx.responseComplete();
            HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getExternalContext().getResponse();
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            httpServletResponse.setHeader("Content-disposition", "attachment; filename=" + strfileName);//strfileName
            httpServletResponse.setContentLength((int) exportFile.length());//exportFile
            httpServletResponse.setContentType("application/x-download");
            //httpServletResponse.setContentType("application/vnd.ms-excel");
            byte[] b = new byte[1024];
            int i = 0;
            FileInputStream fis = new java.io.FileInputStream(exportFile);
            while ((i = fis.read(b)) > 0) {
                servletOutputStream.write(b, 0, i);
            }
            servletOutputStream.flush();
            ctx.responseComplete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void defaults() {
        if ("0".equals(exp.getNumberStatus().trim()) && "C".equalsIgnoreCase(curPerRole().trim())) {
            exp.setAuditor(curPerName().trim());
            exp.setAuditDate(new Date());
        }

        payWay = exp.getPayStyle().getCode();

        if ("2".equals(exp.getNumberStatus().trim()) && "P".equalsIgnoreCase(curPerRole().trim())) {
            exp.setPayer(curPerName().trim());
            exp.setPayaccount(exp.getCheckaccount());
            exp.setReceive(exp.getFeePer().getCpsn_name());
            exp.setPayDate(new Date());
            forCashPaid();
        }
    }

    public void forCashPaid() {
        if (!Null.check(exp.getPayStyle().getType()) && Null.check(exp.getCashPaid())) {
            if (exp.getPayStyle().getType().equals("0")) {
                exp.setCashPaid("1");
            } else {
                exp.setCashPaid("0");
            }
        }
    }

    public void initCheckViewList() {
        Map map = new HashMap();
        map.put("voustatus", "0");
        map.put("orgCode", curOrgCode().trim());
        loanbilllist = IbatisTemplate.queryForList(nameSpace + "queryLoanBillViewList", map);
        loanCheckViewModel.setWrappedData(loanbilllist);
    }

    public void showFromCheckView(Expense expense, DataModel viewModel) {
        this.setExp(expense);
        index = viewModel.getRowIndex();
        loanbilllist = (List<Expense>) viewModel.getWrappedData();
        linkedli.clear();
        linkedli.addAll(loanbilllist);
        defaults();
        exp.setCheckaccount(exp.getTotal());
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }
        NavigationTool.getSelectedUrl("/page/pay/check/operation/loanbill.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
    }

    public void showFromPayView(Expense expense, DataModel viewModel) {
        this.setExp(expense);
        index = viewModel.getRowIndex();
        loanbilllist = (List<Expense>) viewModel.getWrappedData();
        linkedli.clear();
        linkedli.addAll(loanbilllist);
        defaults();
        if (index == 0) {
            dis.setFirst(true);
            dis.setPreviouse(true);
            dis.setNext(false);
            dis.setLast(false);
        }
        if (index > 0 && index < linkedli.size() - 1) {
            dis.setFirst(false);
            dis.setLast(false);
            dis.setNext(false);
            dis.setPreviouse(false);
        }
        if (index == linkedli.size() - 1) {
            dis.setLast(true);
            dis.setNext(true);
            dis.setPreviouse(false);
            dis.setFirst(false);
        }

        NavigationTool.getSelectedUrl("/page/pay/payment/operation/loanbill.xhtml");
        FacesContext.getCurrentInstance().renderResponse();
    }

    public Expense getExp() {
        return exp;
    }

    public void setExp(Expense exp) {
        this.exp = exp;
    }

    public boolean isAddOrUpdate() {
        return addOrUpdate;
    }

    public void setAddOrUpdate(boolean addOrUpdate) {
        this.addOrUpdate = addOrUpdate;
    }

    public boolean isShowAble() {
        return showAble;
    }

    public void setShowAble(boolean showAble) {
        this.showAble = showAble;
    }

    public boolean isDeleteable() {
        return deleteable;
    }

    public void setDeleteable(boolean deleteable) {
        this.deleteable = deleteable;
    }

    public boolean isSubmitOrNot() {
        return submitOrNot;
    }

    public void setSubmitOrNot(boolean submitOrNot) {
        this.submitOrNot = submitOrNot;
    }

    public QueryVouchers getQlb() {
        return qlb;
    }

    public void setQlb(QueryVouchers qlb) {
        this.qlb = qlb;
    }

    public List<CostItemAccount> getExpacc() {
        return expacc;
    }

    public void setExpacc(List<CostItemAccount> expacc) {
        this.expacc = expacc;
    }

    public List<Expense> getLoanbilllist() {
        return loanbilllist;
    }

    public void setLoanbilllist(List<Expense> loanbilllist) {
        this.loanbilllist = loanbilllist;
    }

    public ListDataModel getModel() {
        return model;
    }

    public void setModel(ListDataModel model) {
        this.model = model;
    }

    public boolean isSaveOrNot() {
        return saveOrNot;
    }

    public void setSaveOrNot(boolean saveOrNot) {
        this.saveOrNot = saveOrNot;
    }

    public boolean isUpdateOrNot() {
        return updateOrNot;
    }

    public void setUpdateOrNot(boolean updateOrNot) {
        this.updateOrNot = updateOrNot;
    }

    public LinkedList<Expense> getLinkedli() {
        return linkedli;
    }

    public void setLinkedli(LinkedList<Expense> linkedli) {
        this.linkedli = linkedli;
    }

    public boolean isGetFirstOrNot() {
        return getFirstOrNot;
    }

    public void setGetFirstOrNot(boolean getFirstOrNot) {
        this.getFirstOrNot = getFirstOrNot;
    }

    public Disabled getDis() {
        return dis;
    }

    public void setDis(Disabled dis) {
        this.dis = dis;
    }
    //

    private String curPerNum() {
        return LoginParam.getPer().getCpsn_number();
    }

    private String curPerName() {
        return LoginParam.getPer().getCpsn_name();
    }

    private String curDeptCode() {
        return LoginParam.getDept().getCode();
    }

    private String curDeptName() {
        return LoginParam.getDept().getName();
    }

    private Date curLoginDate() {
        return LoginParam.getLoginDate();
    }

    private Integer curIyear() {
        return LoginParam.getIyear();
    }

    private String curOrgCode() {
        return LoginParam.getOrg().getCode();
    }

    public UIDataTable getCheckData() {
        return checkData;
    }

    public void setCheckData(UIDataTable checkData) {
        this.checkData = checkData;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }

    public DataModel<Expense> getLoanbillModel() {
        return loanbillModel;
    }

    public void setLoanbillModel(DataModel loanbillModel) {
        this.loanbillModel = loanbillModel;
    }

    public UIDataTable getPayData() {
        return payData;
    }

    public void setPayData(UIDataTable payData) {
        this.payData = payData;
    }

    public List<SelectItem> getPayStyleList() {
        return payStyleList;
    }

    public void setPayStyleList(List<SelectItem> payStyleList) {
        this.payStyleList = payStyleList;
    }

    public String getPayWay() {
        return payWay;
    }

    public void setPayWay(String payWay) {
        this.payWay = payWay;
    }

    public String getPayWayType() {
        return payWayType;
    }

    public void setPayWayType(String payWayType) {
        this.payWayType = payWayType;
    }

    private String curPerRole() {
        return LoginParam.getPer().getRole();
    }

    public DataModel getLoanCheckViewModel() {
        return loanCheckViewModel;
    }

    public void setLoanCheckViewModel(DataModel loanCheckViewModel) {
        this.loanCheckViewModel = loanCheckViewModel;
    }

    public static String getNameSpace() {
        return nameSpace;
    }

    public static void setNameSpace(String nameSpace) {
        LoanBillBean.nameSpace = nameSpace;
    }

    public DataModel<FinancialProject> getFinProjModel() {
        return finProjModel;
    }

    public void setFinProjModel(DataModel<FinancialProject> finProjModel) {
        this.finProjModel = finProjModel;
    }

    public List<SelectItem> getSelectItemList() {
        List<SelectItem> selectItemList = new ArrayList<SelectItem>();
        selectItemList.add(new SelectItem("0,3", "未审核"));
        selectItemList.add(new SelectItem("2,4,6", "已审核"));
        return selectItemList;
    }

    public List<SelectItem> getPayStatusList() {
        List<SelectItem> payStatusList = new ArrayList<SelectItem>();
        payStatusList.add(new SelectItem("0,2,3", "未支付"));
        payStatusList.add(new SelectItem("4,6", "已支付"));
        return payStatusList;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
}
